<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <!-- 左列 -->
        <el-col :span="14">
          <el-form-item label="护照号码" prop="passportNumber">
            <el-input v-model="formData.passportNumber" placeholder="请输入护照号码"/>
          </el-form-item>

          <el-form-item label="人员姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入姓名"/>
          </el-form-item>

          <el-form-item label="人员性别&nbsp;&nbsp;" prop="sex">
            <el-radio-group v-model="formData.sex">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :value="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="管控单位" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              :default-expanded-keys="defaultExpandedKeys"
              placeholder="请选择管控单位"
            />
          </el-form-item>
        </el-col>

        <!-- 右列 -->
        <el-col :span="10">
          <el-form-item label="头像" prop="avatar" class="no-label-width">
            <UploadImg v-model="formData.avatar" :limit="1" :is-show-tip="false"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="人员分类" prop="groupId">
        <MemberGroupSelect v-model="formData.groupId"/>
      </el-form-item>

      <!-- 下方其他表单项 -->
      <el-form-item label="人员标签&nbsp;&nbsp;" prop="tagIds">
        <MemberTagSelect v-model="formData.tagIds" show-add/>
      </el-form-item>

      <el-form-item label="电话号码&nbsp;&nbsp;" prop="phoneNumber">
        <el-input v-model="formData.phoneNumber" placeholder="请输入电话号码，多个逗号隔开"/>
      </el-form-item>

      <el-form-item label="车牌号码&nbsp;&nbsp;" prop="carNumber">
        <el-input v-model="formData.carNumber" placeholder="请输入车牌号码，多个逗号隔开"/>
      </el-form-item>

      <el-form-item label="户&nbsp;籍&nbsp;地&nbsp;&nbsp;&nbsp;" prop="birthPlace">
        <el-input v-model="formData.birthPlace" placeholder="请输入户籍地"/>
      </el-form-item>

      <el-form-item label="居&nbsp;住&nbsp;地&nbsp;&nbsp;&nbsp;" prop="liveAddress">
        <el-input v-model="formData.liveAddress" placeholder="请输入居住地"/>
      </el-form-item>

      <el-form-item label="人员备注&nbsp;&nbsp;" prop="remark">
        <el-input
          v-model="formData.remark"
          placeholder="请输入备注"
          type="textarea"
          :rows="2"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as UserApi from '@/api/member/user'
import * as AreaApi from '@/api/system/area'
import MemberTagSelect from '@/views/member/tag/components/MemberTagSelect.vue'
import MemberGroupSelect from '@/views/member/group/components/MemberGroupSelect.vue'
import {defaultProps, handleTree} from "@/utils/tree";
import {DeptVO} from "@/api/system/dept";
import * as DeptApi from '@/api/system/dept'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const deptList = ref<Tree[]>([]) // 树形结构
const depts = ref<DeptVO[]>([]) // 树形结构
const defaultExpandedKeys = ref<number[]>([]) // 默认展开的节点 ID 数组

const formData = ref({
  id: undefined,
  mobile: undefined,
  idcard: undefined,
  password: undefined,
  status: undefined,
  nickname: undefined,
  avatar: undefined,
  name: undefined,
  sex: undefined,
  areaId: undefined,
  birthday: undefined,
  mark: undefined,
  tagIds: [],
  groupId: undefined,
  deptId: undefined,
  deptName: undefined as string | undefined, // 明确允许 undefined

  country: undefined,
  nation: undefined,
  remark: undefined,
  phoneNumber: undefined,
  carNumber: undefined,
  passportNumber: undefined,
  faith: undefined,
  enFirstName: undefined,
  enSecondName: undefined,
  liveAddress: undefined,
  birthPlace: undefined,
  foreigner: 1
})
const formRules = reactive({
  passportNumber: [{ required: true, message: '护照号码不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '管控单位不能为空', trigger: 'blur' }],
  groupId: [{ required: true, message: '人员分类不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '人员姓名不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const areaList = ref([]) // 地区列表

// 加载部门数据
const loadDeptData = async () => {
  depts.value = await DeptApi.getSimpleDeptList()
  deptList.value = handleTree(depts.value)
  // 默认展开一级节点（假设一级部门的 parentId 是 0 或 undefined）
  defaultExpandedKeys.value = depts.value
    .filter(dept => (!dept.parentId || dept.parentId === 0) && dept.id !== undefined)
    .map(dept => dept.id!) // 确保非空
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
  // 加载部门树
  await loadDeptData();
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    formData.value.foreigner = 1
    // 设置选中的部门名称（如果 deptId 存在）
    if (formData.value.deptId) {
      const dept = findDeptById(formData.value.deptId);
      formData.value.deptName = dept?.name || '';
    }
    const data = formData.value as unknown as UserApi.UserVO
    if (formType.value === 'create') {
      // 说明：目前暂时没有新增操作。如果自己业务需要，可以进行扩展
      await UserApi.createUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 查找部门 */
const findDeptById = (id: number) => {
  for (const dept of depts.value) {
    if (dept.id === id) return dept;
  }
  return undefined;
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    idcard: undefined,
    mobile: undefined,
    password: undefined,
    status: undefined,
    nickname: undefined,
    avatar: undefined,
    name: undefined,
    sex: undefined,
    areaId: undefined,
    birthday: undefined,
    mark: undefined,
    tagIds: [],
    groupId: undefined,
    deptId: undefined,
    deptName: undefined,
    country: undefined,
    nation: undefined,
    remark: undefined,
    phoneNumber: undefined,
    carNumber: undefined,
    passportNumber: undefined,
    faith: undefined,
    enFirstName: undefined,
    enSecondName: undefined,
    liveAddress: undefined,
    birthPlace: undefined,
    foreigner: 2
  }
  formRef.value?.resetFields()
}
</script>
